package com.guchenbo.example.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServerExample {
    public static void main(String[] args) {
        int serverPort = 12345; // 服务器端口号

        // 创建用于接受客户端连接的事件循环组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 创建用于处理客户端请求的事件循环组
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                            .group(bossGroup, workerGroup)
                            .channel(NioServerSocketChannel.class)
                            .childHandler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel ch) {
                                    ch.pipeline().addLast(new ServerHandler()); // 自定义处理器
                                }
                            })
                            .childOption(ChannelOption.SO_KEEPALIVE, true);

            // 绑定端口，等待客户端连接
            serverBootstrap.bind(serverPort).sync().channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 处理从客户端接收的数据
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] data = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(data);
        String message = new String(data);
        System.out.println("Received from client: " + message);

        // 回复客户端
        String response = "Hello, client!";
        ByteBuf responseBuf = Unpooled.copiedBuffer(response.getBytes());
        ChannelFuture future = ctx.writeAndFlush(responseBuf);

        if ("bye".equals(message)) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

